package com.flyme.module.file.provider.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.Md5Utils;
import com.polyv.live.bean.result.channel.PLChannelCreateResult;
import com.polyv.live.util.JsonUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

public class PoylUtil2 {
    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
            .setConnectionRequestTimeout(15000).build();
    /**
     * http://live.polyv.net/secure/user/detail.htm
     * http://live.polyv.net/secure/user/app.htm
     */
    private static final String APP_USER_ID = "c0f891cf2e";
    private static final String APP_ID = "f8qdgpjlae";
    private static final String APP_SECRET = "564333d2980b49a699d589daae9b5f85";
    private static final String CREATE_CHANNEL_URL = "http://api.polyv.net/live/v2/channels/";

    public static void main(String[] args) {
        PoylUtil2 demo = new PoylUtil2();
        demo.crateChannel("测试","alone");
    }

    public static PLChannelCreateResult crateChannel(String name,String secne) {
        PLChannelCreateResult plChannelCreateResult=null;
        Map<String, String> params = new HashMap<>();
        params.put("appId", APP_ID);
        params.put("channelPasswd", "12345");
        params.put("name", name);
        params.put("scene", secne);
        params.put("timestamp", System.currentTimeMillis()+"");
        params.put("userId", APP_USER_ID);
        String sign = generateSign(params, APP_SECRET);
        params.put("sign", sign);
        String result = sendHttpPost(CREATE_CHANNEL_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String status=jsonObject.get("code").toString();
        if(status.equals("200")){
            String data=jsonObject.get("data").toString();
             plChannelCreateResult=JsonUtil.parseObject(data,PLChannelCreateResult.class);
        }
        return plChannelCreateResult;
    }

    public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
        HttpPost httpPost = new HttpPost(httpUrl);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

    private static String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    private static String generateSign(Map<String, String> parray, String secretKey) {
        Map<String, String> params = paraFilter(parray);
        String concatedStr = concatParams(params);
        String plain = secretKey + concatedStr + secretKey;
        String encrypted = Md5Utils.getMD5(plain.getBytes());
        String upperCase = encrypted.toUpperCase();
        return upperCase;
    }

    private static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    private static String concatParams(Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            sb.append(key).append(value);
        }
        return sb.toString();
    }
}
